import interceptors from "./interceptors";

export type HeaderType = { [key: string]: string };
export type OtherRequestOptionsType = Omit<UniApp.RequestOptions, 'url' | 'data' | 'method'>;

export async function request(params: UniApp.RequestOptions) {
  const { url, method = "GET", data = {}, header = {}, ...rest } = params;
  const headers: HeaderType = {
    'content-type': "application/json",
    ...header
  }
  if(uni.getStorageSync('token')){
    headers['Authorization'] = "Bearer " + uni.getStorageSync('token');
  }

  return new Promise((resolve, reject)=> {
    uni.request({
      url: url,
      data: data,
      method: method,
      header: headers,
      success: (res) => interceptors(res).then((d)=> resolve(d)).catch((e)=> reject(e)),
      fail: (res) => reject(res),
      ...rest
    })
  });
}

export const get = (url: string, data = {}, rest: OtherRequestOptionsType = {}) => {
  return request({ url, method: "GET", data, ...rest });
}

export const post = (url: string, data = {}, rest: OtherRequestOptionsType = {}) => {
  return request({ url, method: "POST", data, ...rest });
}

export const put = (url: string, data = {}, rest: OtherRequestOptionsType = {}) => {
  return request({ url, method: "PUT", data, ...rest });
}

export const del = (url: string, data = {}, rest: OtherRequestOptionsType = {}) => {
  return request({ url, method: "DELETE", data, ...rest });
}
